package com.example.OnlineStorage.service.ShareFilePermissions;

import com.example.OnlineStorage.Dao.ShareFilePermissionsDao;
import com.example.OnlineStorage.Dao.ShareFilesDao;
import com.example.OnlineStorage.exception.CustomException;
import com.example.OnlineStorage.pojo.entity.Pagination;
import com.example.OnlineStorage.pojo.entity.ShareFilePermissions;
import com.example.OnlineStorage.pojo.entity.ShareFiles;
import com.example.OnlineStorage.pojo.entity.User;
import com.example.OnlineStorage.util.PermissionsControl;
import com.example.OnlineStorage.util.Redis;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@Slf4j
public class IShareFilePermissionsService implements ShareFilePermissionsService {

    private final ShareFilePermissionsDao shareFilePermissionsDao;
    private final ShareFilesDao shareFilesDao;

    public IShareFilePermissionsService(ShareFilePermissionsDao shareFilePermissionsDao, ShareFilesDao shareFilesDao) {
        this.shareFilePermissionsDao = shareFilePermissionsDao;
        this.shareFilesDao = shareFilesDao;
    }


    /**
     * 修改共享文件夹权限
     *
     * @param shareFileId 共享文件夹ID
     * @param userId 要修改的用户
     * @param permissions 要修改为的权限位
     * @param UUID      Token
     */
    @SneakyThrows
    @Override
    public void updateShareFilePermissionsByUserId(Long shareFileId, Long userId, Long permissions, String UUID) {
        try {
            User user = User.fromJson(Redis.HGET(Redis.GET(UUID), "user"));

            ShareFiles shareFiles = shareFilesDao.select(shareFileId);
            if(shareFiles==null){
                throw new RuntimeException("共享文件夹不存在.");
            }
            if(Objects.equals(shareFiles.getCreateUserId(), userId)){
                throw new RuntimeException("无法修改共享文件夹创建者的权限.");
            }
            ShareFilePermissions shareFilePermissions = new ShareFilePermissions();
            shareFilePermissions.setShareFilesId(shareFileId);
            shareFilePermissions.setUserId(user.getId());
            Long MenderOfPermissions = shareFilePermissionsDao.select(shareFilePermissions);
            if(MenderOfPermissions==null){
                throw new RuntimeException("没有权限修改.");
            }
            if(!PermissionsControl.isAll(MenderOfPermissions)){
                throw new RuntimeException("没有权限修改.");
            }
            if(Objects.equals(user.getId(), userId)){
                throw new RuntimeException("无法修改自己的权限");
            }
            shareFilePermissions.setPermissions(permissions);
            shareFilePermissions.setUserId(userId);
            Long CapturedOfPermissions = shareFilePermissionsDao.select(shareFilePermissions);
            if(CapturedOfPermissions==null){
                throw new RuntimeException("要修改的权限不存在.");
            }
            if(PermissionsControl.isAll(CapturedOfPermissions)){
                throw new RuntimeException("无法修改跟自己同级的成员权限.");
            }
            shareFilePermissionsDao.update(shareFilePermissions);
        } catch (Exception e) {
            if (e.getCause() != null) {
                String Cause = e.getCause().toString();
                if (Cause.startsWith("java.sql.SQL")) {
                    throw new CustomException(500, "服务器异常.请联系管理员.");
                }
            }
            throw new CustomException(400, e.getMessage());
        }
    }

    /**
     * 根据共享id查询该共享的所有成员权限信息
     *
     * @param shareFileId 共享文件id
     * @param page 第几页
     * @return 返回一页的成员权限信息
     */
    @SneakyThrows
    @Override
    public ShareFilePermissions[] getShareFilePermissionsByShaFileId(Long shareFileId, Integer page) {
        try {
            return shareFilePermissionsDao.selectByShareFileId(shareFileId,new Pagination(page));
        } catch (Exception e){
            if (e.getCause() != null) {
                String Cause = e.getCause().toString();
                if (Cause.startsWith("java.sql.SQL")) {
                    throw new CustomException(500, "服务器异常.请联系管理员.");
                }
            }
            throw new CustomException(400, e.getMessage());
        }
    }

    /**
     * 查询一个共享文件夹有多少个成员
     *
     * @param shareFileId 共享文件夹ID
     * @return 返回共享文件夹的成员数量
     */
    @SneakyThrows
    @Override
    public Long getShareFilePermissionsCountByShareFileId(Long shareFileId){
        try {
            return shareFilePermissionsDao.selectCountByShareFileId(shareFileId);
        } catch (Exception e){
            if (e.getCause() != null) {
                String Cause = e.getCause().toString();
                if (Cause.startsWith("java.sql.SQL")) {
                    throw new CustomException(500, "服务器异常.请联系管理员.");
                }
            }
            throw new CustomException(400, e.getMessage());
        }
    }

    /**
     * 查询用户加入的共享文件夹列表
     *
     * @param page 第几页
     * @param UUID Token
     * @return 返回一页用户加入的共享文件夹信息
     */
    @SneakyThrows
    @Override
    public ShareFilePermissions[] getShareFilePermissionsByUserId(Integer page, String UUID){
        try{
            User user = User.fromJson(Redis.HGET(Redis.GET(UUID),"user"));
            return shareFilePermissionsDao.selectByUserId(user.getId(),new Pagination(page));
        } catch (Exception e){
            if (e.getCause() != null) {
                String Cause = e.getCause().toString();
                if (Cause.startsWith("java.sql.SQL")) {
                    throw new CustomException(500, "服务器异常.请联系管理员.");
                }
            }
            throw new CustomException(400, e.getMessage());
        }

    }

    /**
     * 搜索共享文件夹
     *
     * @param name 搜索关键字
     * @return 返回符合的共享文件夹列表
     */
    @SneakyThrows
    @Override
    public ShareFiles[] selectByName(String name){
        try{
            return shareFilesDao.selectByName(name);
        } catch (Exception e){
            if (e.getCause() != null) {
                String Cause = e.getCause().toString();
                if (Cause.startsWith("java.sql.SQL")) {
                    throw new CustomException(500, "服务器异常.请联系管理员.");
                }
            }
            throw new CustomException(400, e.getMessage());
        }
    }

    /**
     * 加入一个共享文件夹
     *
     * @param shareFileId 共享文件夹ID
     * @param UUID Token
     */
    @SneakyThrows
    @Override
    public void joinShareFiles(Long shareFileId, String UUID){
        try{
            User user = User.fromJson(Redis.HGET(Redis.GET(UUID),"user"));
            ShareFilePermissions shareFilePermissions = new ShareFilePermissions();
            shareFilePermissions.setUserId(user.getId());
            shareFilePermissions.setShareFilesId(shareFileId);
            Long Permissions = shareFilePermissionsDao.select(shareFilePermissions);
            if(Permissions!=null){
                throw new RuntimeException("你已经加入该共享文件夹了，无需二次加入");
            }
            shareFilePermissions.setPermissions(PermissionsControl.commonPermissions());
            shareFilePermissionsDao.insert(shareFilePermissions);
        } catch (Exception e){
            if (e.getCause() != null) {
                String Cause = e.getCause().toString();
                if (Cause.startsWith("java.sql.SQL")) {
                    throw new CustomException(500, "服务器异常.请联系管理员.");
                }
            }
            throw new CustomException(400, e.getMessage());
        }
    }


    /**
     * 获取共享文件夹的文件信息
     * @param shareFileId 共享文件夹ID
     * @param UUID Token
     * @return 共享文件夹的所有文件信息
     */
    @SneakyThrows
    @Override
    public String getShareFilesFileDataJson(Long shareFileId, String UUID){
        try{
            User user = User.fromJson(Redis.HGET(Redis.GET(UUID),"user"));
            ShareFilePermissions shareFilePermissions = new ShareFilePermissions();
            shareFilePermissions.setShareFilesId(shareFileId);
            shareFilePermissions.setUserId(user.getId());
            Long Permissions = shareFilePermissionsDao.select(shareFilePermissions);
            if(Permissions==null){
                throw new RuntimeException("没有权限获取共享文件夹信息");
            }
            ShareFiles shareFiles = shareFilesDao.select(shareFileId);
            if(shareFiles==null){
                throw new RuntimeException("共享文件夹不存在.");
            }
            return shareFiles.getFileDataJson();
        } catch (Exception e){
            if (e.getCause() != null) {
                String Cause = e.getCause().toString();
                if (Cause.startsWith("java.sql.SQL")) {
                    throw new CustomException(500, "服务器异常.请联系管理员.");
                }
            }
            throw new CustomException(400, e.getMessage());
        }
    }
}
